<template>
  <div class="create-community w100 h100">
    <div class="label">
      <img src="../../../../../static/image/system/community.png" alt="">
      <div class="name">{{name}}</div>
    </div>
    <div class="map w100 h100">
      <div id="map" class=" w100 h100"></div>
      <div class="community-pannel">
        <community-box :community-form="communityForm" :is-view="false"
                       @search="search" @select="select" @hide="hideDialog"></community-box>
      </div>
    </div>
  </div>
</template>

<script>
  // import { regionData } from 'element-china-area-data'
  import { regionData } from 'static/js/regionData'
  import BMap from 'BMap'
  import CommunityBox from './CommunityBox'
  import Config from '../../../../config'
  import axios from 'axios'
  import jsonp from 'jsonp'
  export default {
    name: 'CreateCommunity',
    components: {
      CommunityBox
    },
    data () {
      return {
        map: null,
        cb: null,
        communityForm: {
          areaName: '',
          communityName: '',
          position: '',
          // dfdf
          devtype: 'nbiot',
          devname: 'fireplug',
          site_name: '环普腾飞科汇城',
          site_serialno: '',
          country: '86',
          province: '610000',
          city: '610100',
          district: '610113',
          street: '鱼化寨',
          community: '环普腾飞科汇城',
          address: '',
          gps_lon: '108.12345',
          gps_lat: '34.12345',
          site_phone: '',
          site_status: 'normal'
        }
      }
    },
    computed: {
      name () {
        const path = this.$route.path
        if (path.includes('create')) {
          return `新增场所`
        }
        return '场所编辑'
      }
    },
    mounted () {
      this.initMap()
      this.initLocal()
      const path = this.$route.path
      if (path.includes('edit')) { // 编辑
        this.getCommunityById()
      }
      console.log(regionData)
    },
    methods: {
      /**
       * 初始化地图
       * */
      initMap () {
        if (this.map) {
          return
        }
        this.map = new BMap.Map('map', {enableMapClick:false});    // 创建Map实例
        const point = new BMap.Point(114, 34)
        this.map.centerAndZoom(point, 15);      // 初始化地图,用城市名设置地图中心点
        this.map.enableScrollWheelZoom(true)
        // 新增点击地图添加场所方式
        const path = this.$route.path
        if (path.includes('edit')) { // 不允许编辑
          return
        }
        this.map.addEventListener('click', e => { //给地图添加点击事件
          const point = e.point
          const marker = new BMap.Marker(point)
          this.map.clearOverlays()
          this.map.addOverlay(marker)
          this.getLocation(point);
        });
      },
      /**
       * 通过地图上的点来录入场所信息
       * */
      getLocation (point) {
        const url = `//api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=${point.lat},${point.lng}&output=json&pois=1&ak=Wucv3BaiZ6Ct6bIAaNDNgGOzpEhDxOGu`
        jsonp(url, null, (err, res) => {
          if (err) {
            this.$message.warning('获取地理数据错误')
          } else {
            const result = res.result
            const addComp = result.addressComponent
            console.log('res ', result)
            const districtCode = addComp.adcode
            const provinceCode =  this.$substring.province(districtCode) // `${districtCode.substring(0, 2)}0000`
            const cityCode = this.$substring.city(districtCode) // districtCode === '419001' ? '419001' : `${districtCode.substring(0, 4)}00`
            const province = this.getAreaObjByValue(regionData, provinceCode)
            const city = this.getAreaObjByValue(province.children, cityCode)
            const district = this.getAreaObjByValue(city.children, districtCode)
            // this.communityForm = null
            const form = {
              areaName: `${addComp.province}${addComp.city}${addComp.district}`,
              communityName: result.poiRegions && result.poiRegions[0] && result.poiRegions[0].name || '',
              position: `${parseInt(point.lng)}，${parseInt(point.lat)}`,
              devtype: 'nbiot',
              devname: 'fireplug',
              site_name: '',
              country: '86',
              province: province.value,
              city: city.value,
              district: district ? district.value : '',
              street: addComp.street + addComp.street_number,
              community: '',
              address: result.formatted_address,
              gps_lon: point.lng,
              gps_lat: point.lat,
              site_phone: '',
              site_status: 'normal'
            }
            console.log('before ', this.communityForm)
            this.communityForm = {...this.communityForm, ...form}
            console.log('after ', this.communityForm)
          }
        })
      },
      /**
       * 初始化百度地图LocalSearch
       * */
      initLocal () {
        if (this.local) {
          return
        }
        this.local = new BMap.LocalSearch(this.map, {
          renderOptions:{map: this.map}
        })
        this.local.setSearchCompleteCallback(res => {
          const arr = res.Br
          if (arr.length === 0) {
            this.$message.warning('没有找到符合要求的结果')
          }
          arr.forEach(item => {
            item.value = item.title
          })
          console.log(arr)
          if (!this.cb) {
            return
          }
          this.cb(arr)
        })
        this.local.setMarkersSetCallback(res => {
          res.forEach(item => {
            const marker = item.marker
            marker.addEventListener('click', () => {
              console.log(item)
              this.setCommunityForm(item)
            })
          })
        })
      },
      /**
       * 根据id获取场所信息
       * */
      getCommunityById () {
        const url = `${Config.DEVICE_MANAGE_URL}/final_equipsite/query`
        const query = this.$route.params.id.split('-') // [site_serialno, district]
        console.log(query)
        const param = {
          page: 0,
          size: 1,
          site_serialno: query[0],
          district: query[1]
        }
        this.$http.get(url, param)
          .then(data => {
            const list = data.array
            if (list.length === 0) {
              this.$message.warning('查询到的结果为0')
              return
            }
            this.communityForm = null
            this.communityForm = list[0]
            this.handleData()
          })
      },
      /**
       * 对数据进行预处理
       * */
      handleData () {
        const form = this.communityForm
        const province = this.getAreaObjByValue(regionData, form.province)
        const city = this.getAreaObjByValue(province.children, form.city)
        const district = this.getAreaObjByValue(city.children, form.district)
        this.communityForm.areaName = `${province.label}${city.label}${district.label}`
        this.communityForm.communityName = form.site_name
        this.communityForm.position = `${parseInt(form.gps_lon)}，${parseInt(form.gps_lat)}`
        const point = {lat: form.gps_lat, lng: form.gps_lon}
        this.addMarker(point)
        console.log('this.communityForm ', this.communityForm)
      },
      /**
       * 添加marker
       * */
      addMarker (point) {
        this.map.clearOverlays()
        console.log(point)
        const bdPoint = new BMap.Point(point.lng, point.lat)
        const marker = new BMap.Marker(bdPoint)
        this.map.addOverlay(marker)
        this.map.setCenter(bdPoint)
      },
      /**
       * 确定当前场所信息
       * @param {Object} item
       * */
      setCommunityForm (item) {
        if (!item.province) {
          this.$message.warning('请查询合法的场所')
          return
        }
        const province = this.getAreaObj(regionData, item.province)
        const city = this.getAreaObj(province.children, item.city)
        this.geocoder(item.point)
          .then(res => {
            const district = this.getAreaObj(city.children, res.addressComponents.district)
            // this.communityForm = null
            const form = {
              areaName: `${item.province}${item.city}`,
              communityName: item.title,
              position: `${parseInt(item.point.lng)}，${parseInt(item.point.lat)}`,
              devtype: 'nbiot',
              devname: 'fireplug',
              site_name: item.title,
              country: '86',
              province: province.value,
              city: city.value,
              district: district.value,
              street: '',
              community: item.title,
              address: item.address,
              gps_lon: item.point.lng,
              gps_lat: item.point.lat,
              site_phone: item.phoneNumber | '',
              site_status: 'normal'
            }
            this.communityForm = {...this.communityForm, ...form}
          })
      },
      /**
       * 逆地址编码
       * @return {Promise(String)} district
       * */
      geocoder (point) {
        return new Promise((resolve, reject) => {
          const geoc = new BMap.Geocoder()
          geoc.getLocation(point, res => {
            resolve(res)
          })
        })
      },
      /**
       * 获取区域信息
       * @param {Array} arr
       * @return {Object} obj
       * */
      getAreaObj (arr, label) {
        let obj = null
        arr.some(item => {
          if (label === item.label) {
            obj = item
            return true
          }
        })
        return obj
      },
      /**
       * 获取区域信息
       * @param {Array} arr
       * @param {Array} value
       * @return {Object} obj
       * */
      getAreaObjByValue (arr, value) {
        let obj = null
        arr.some(item => {
          if (value === item.value) {
            obj = item
            return true
          }
        })
        return obj
      },
      getAreaObjByLabel (arr, label) {
        let obj = null
        arr.some(item => {
          if (label === item.label) {
            obj = item
            return true
          }
        })
        return obj
      },
      /**
       * 触发百度地图本地搜索
       * */
      search (str, cb) {
        this.map.clearOverlays()
        if (!str) {
          return
        }
        this.cb = cb
        this.local.search(str)
      },
      /**
       * 下拉框选中的值，地图上只保留这一个点
       * */
      select (item) {
        this.setCommunityForm(item)
        this.showNowMarker(item)
      },
      /**
       * 显示当前的marker
       * */
      showNowMarker (item) {
        this.map.closeInfoWindow()
        this.map.clearOverlays()
        const marker = new BMap.Marker(item.point)
        this.map.addOverlay(marker)
        // 构造弹出气泡
        let content = `
          <div class="BMap_bubble_content" style="width: auto; height: auto;">
            <div class="BMap_bubble_title"
                 style="overflow: hidden; height: auto; line-height: 24px; white-space: nowrap; width: auto;">
                <p style="width:210px;font:bold 14px/16px arial,sans-serif;margin:0;color:#cc5522;white-space:nowrap;overflow:hidden">
                    ${item.value}<a target="_blank"
                                  href="${item.detailUrl}"
                                  style="margin-left:5px;font-size:12px;color:#3d6dcc;font-weight:normal;text-decoration:none;">详情»</a>
                </p>
            </div>
        </div>
        <div class="BMap_bubble_content" style="width: auto; height: auto;">
            <div style="font:12px arial,sans-serif;margin-top:10px">
                <table cellspacing="0" style="overflow:hidden;table-layout:fixed;width:100%;font:12px arial,sans-serif">
                    <tbody>
                    <tr>
                        <td style="vertical-align:top;width:38px;white-space:nowrap;word-break:keep-all">地址：&nbsp;</td>
                        <td style="line-height:16px">${item.address}&nbsp;</td>
                    </tr>
                    `
        if (item.phoneNumber) {
          content += `
            <tr>
              <td style="vertical-align:top;">电话：</td>
              <td>${item.phoneNumber}</td>
            </tr>
            </tbody>
            </table>
            </div>
            </div>`
        } else {
          content += `</tbody>
          </table>
          </div>
          </div>`
        }
        const infoWindow = new BMap.InfoWindow(content)
        marker.openInfoWindow(infoWindow)
      },
      /**
       * 关掉dialog
       * */
      hideDialog (success) {
        if (success === 'cancel') {
          this.$router.go(-1)
          return
        }
        if (success === true) {
          this.$message.success('保存成功')
          this.$router.go(-1)
          return
        }
        this.$message.warning('保存失败')
      }
    }
  }
</script>

<style lang="scss" scoped>
  .create-community {
    box-sizing: border-box;
    padding: 0 12px 12px 12px;
    background-color: #fff;
    .label {
      height: 44px;
      display: flex;
      align-items: center;
      img {
        height: 20px;
        margin-right: 8px;
      }
      .name {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }
    }
    .map {
      height: calc(100% - 44px);
      position: relative;
      .map {
        width: 100%;
        height: 100%;
      }
      .community-pannel {
        position: absolute;
        left: 24px;
        top: 24px;
      }
    }
  }
</style>
